<?php

namespace Kollway\Logger\Swagger;

class SwaggerService
{
    protected static $doc_file_url = 'https://kollway-kollway.oschina.io/api-doc/project/';
    protected static $url = 'https://kollway-kollway.oschina.io/api-doc/project/api.html?json=';

    protected $swagger_file = '';

    public function __construct()
    {
        if (empty(env('SWAGGER_FILE'))) {
            exit('请先在 .env 配置 SWAGGER_FILE, 值为 api 文档文件名, 如: manju-api-docs.json');
        }
        $this->swagger_file = env('SWAGGER_FILE');
    }

    /**
     * 获取 api 文档内容, 数组格式
     * @return array
     * @throws \Throwable
     */
    public function getSwaggerArray()
    {
        // 缓存 60 分钟
        return \Cache::remember($this->swagger_file, 60, function () {
            $full_url = static::$doc_file_url . $this->swagger_file;
            $json_content = file_get_contents($full_url);

            $json_array = json_decode($json_content, true);
            if (!$json_array) {
                throw new \Exception('获取 api 文档失败: ' . $full_url);
            }

            return $json_array;
        });
    }

    // 获取 tag、summary
    // 文档路径
    /** @throws \Throwable */
    public function getSwaggerInfo()
    {
        $swagger_array = $this->getSwaggerArray();
        $doc_url = static::$url . '/' . $this->swagger_file . '#';

        $path = request()->getPathInfo();
        if ($doc = array_get($swagger_array, 'paths.' . $path)) {
            $method = key($doc);

            $tag = '';
            // 获取标签信息, 只获取一个
            $tags = $doc[$method]['tags'];
            if (count($tags) > 0) {
                $tag = $tags[0];
            }
            $doc_url .= "/{$tag}/{$method}" . str_replace('/', '_', $path);
            $is_deprecated = isset($doc[$method]['deprecated']) ? intval($doc[$method]['deprecated']) : 0;

            $summary = array_get($doc, $method . '.summary', '');

            $tag = $this->getTag($tag);
            return compact('method', 'tag', 'summary', 'doc_url', 'is_deprecated');
        }

        return null;
    }

    /** @throws \Throwable */
    protected function getTag($tag)
    {
        $swagger_array = $this->getSwaggerArray();
        foreach ($swagger_array['tags'] as $value) {
            if ($value['name'] == $tag) {
                return $value['description'];
            }
        }

        return '';
    }
}